<template>
  <div>
    <canvas
      id="canvas"
      ref="canvas"
      style="position: fixed; left: 0; top: 0"
      @mousedown="canvasonmousedown"
      @touchstart="canvastouchstart"
      @touchmove="canvastouchmove"
      @mousemove="canvasonmousemove"
      @touchend="canvastouchend"
      @mouseup="canvasonmouseup"
    ></canvas>
    <div style="position: relative; z-index: 999">
      <button id="change" @click="eraser">
        切换为{{ status !== "铅笔" ? "铅笔" : "橡皮擦" }}
      </button>
      <button id="AllClean" @click="AllClean">清屏</button>
      <button id="Pdel" @click="Pdel">-</button>
      <span>{{ status }}</span>
      <button id="Padd" @click="Padd">+</button>
      <span id="Pcuxi">当前{{ status }}{{ lineWidth }}</span>
      <button id="upload" @click="upload">上传图片</button>
      <button @click="getimg">获取图片</button>
      <img :src="imgsrc" />
    </div>
    <div style="position: absolute;z-index: 9999;">
      <input type="text" v-model="yuiname">
      <input type="text" v-model="notename">
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      PorE: "P",
      canvas: "",
      ctx: "",
      flag: false,
      iurl: "",
      eraserORpan: "切换为橡皮擦",
      eraserORpanNow: "当前为铅笔",
      status: "铅笔",
      lineWidth: "3",
      imgsrc: "",
      yuiname:'',
      notename:'',
    };
  },
  mounted() {
    let pageWidth = document.documentElement.clientWidth;
    let pageHeight = document.documentElement.clientHeight / 1.5;
    this.$refs.canvas.width = pageWidth;
    this.$refs.canvas.height = pageHeight;
    this.canvas = this.$refs.canvas;
    this.ctx = this.canvas.getContext("2d");
    this.ctx.lineWidth = 3;
    this.ctx.strokeStyle = "red"; //线条
  },
  methods: {
    getimg() {
      fetch(`http://localhost:3000/upload/export?name=${this.yuiname}&notename=${this.notename}`, {
        method: "Get",
      })
        .then((res) => {
          return res.text();
        })
        .then((res) => {
          // console.log(JSON.parse(res));
          let pres = JSON.parse(res)
          // console.log(pres.data[0].mybase)
          if(pres.data[0].mybase.startsWith('data:image/png;base64,')){
            this.imgsrc = pres.data[0].mybase;
          }else{
            console.log('不是base64')
          }
          // console.log(res);
        });
    },
    //按下
    canvasonmousedown() {
      this.flag = true;
      this.ctx.beginPath();
    },
    canvastouchstart() {
      this.flag = true;
      this.ctx.beginPath();
    },
    //鼠标移入绘图
    canvasonmousemove(e) {
      if (!this.flag) return;
      if (this.PorE == "P") {
        this.ctx.lineTo(e.offsetX, e.offsetY); //下一点
        this.ctx.stroke(); //fill()执行填充色  stroke()执行线条
      } else {
        this.ctx.clearRect(e.offsetX - 5, e.offsetY - 5, 10, 10);
      }
    },
    canvastouchmove(e) {
      console.log(e.touches[0]);
      if (!this.flag) return;
      if (this.PorE == "P") {
        this.ctx.lineTo(e.touches[0].clientX - 20, e.touches[0].clientY - 20); //下一点
        this.ctx.stroke(); //fill()执行填充色  stroke()执行线条
      } else {
        this.ctx.clearRect(
          e.touches[0].clientX - 5,
          e.touches[0].clientY - 5,
          10,
          10
        );
      }
    },
    //松开
    canvasonmouseup() {
      this.flag = false;
      this.iurl = this.canvas.toDataURL();
    },
    canvastouchend() {
      this.flag = false;
      this.iurl = this.canvas.toDataURL();
    },
    eraser() {
      if (this.PorE == "E") {
        this.PorE = "P";
        this.status = "铅笔";
      } else {
        this.PorE = "E";
        this.status = "橡皮擦";
      }
    },
    AllClean() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    Pdel() {
      this.ctx.lineWidth--;
      // console.log(this.ctx.lineWidth)
      if (this.lineWidth == 1) return;
      this.lineWidth--;
    },
    Padd() {
      this.ctx.lineWidth++;
      this.lineWidth++;
    },
    upload() {
      let formData = new FormData();
      // var myfile = this.dataURLtoFile(this.canvas.toDataURL(), Date.now() + ".png");//这是转为文件的方法
      var myfile = this.canvas.toDataURL();//base64
      formData.append("file", myfile);
      // var raw = JSON.stringify({
      //   "name": "yui",
      // });
      var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");
      myHeaders.append("Accept", "*/*");
      fetch("http://localhost:3000/upload/album", {
        method: "PUT",
        headers: myHeaders,
        body: JSON.stringify({
          "name": this.yuiname,
          "notename": this.notename,
          "mybase": myfile
        }),
      })
        .then((res) => res.text())
        .then((res) => console.log(res));
    },
    dataURLtoFile(base64Str, fileName) {
      var arr = base64Str.split(","),
        mime = arr[0].match(/:(.*?);/)[1], //base64解析出来的图片类型
        bstr = atob(arr[1]), //对base64串进行操作，去掉url头，并转换为byte   atob为window内置方法
        len = bstr.length,
        ab = new ArrayBuffer(len), //将ASCII码小于0的转换为大于0
        u8arr = new Uint8Array(ab); //
      while (len--) {
        u8arr[len] = bstr.charCodeAt(len);
      }
      // 创建新的 File 对象实例[utf-8内容，文件名称或者路径，[可选参数，type：文件中的内容mime类型]]
      return new File([u8arr], fileName, {
        type: mime,
      });
    },
  },
};
</script>
<!-- <script>
window.onload = function () {
  //当前画笔粗细dom
  let cuxi = document.getElementById("Pcuxi");
  //获得画布元素
  var canvas = document.getElementById("canvas");
  //获得2维绘图对象
  var ctx = canvas.getContext("2d");
  //当前状态是画笔还是橡皮擦
  let PorE = "P";
  //设置线宽
  ctx.lineWidth = 3;
  //颜色
  ctx.strokeStyle = "red"; //线条
  var flag = false;
  //按下
  canvas.onmousedown = function (e) {
    flag = true;
    ctx.beginPath();
  };
  //鼠标移入绘图
  canvas.onmousemove = function (e) {
    if (!flag) return;
    if (PorE == "P") {
      // console.log(e)
      ctx.lineTo(e.offsetX, e.offsetY); //下一点
      ctx.stroke(); //fill()执行填充色  stroke()执行线条
    } else {
      ctx.clearRect(e.offsetX - 5, e.offsetY - 5, 10, 10);
    }
  };
  //松开
  canvas.onmouseup = function (e) {
    flag = false;
    let iurl = canvas.toDataURL();
  };
  document.getElementById("change").onclick = function (e) {
    if (PorE == "E") {
      PorE = "P";
      document.getElementById("change").innerHTML = "切换为橡皮擦";
      cuxi.innerHTML = `当前铅笔${ctx.lineWidth}`;
    } else {
      PorE = "E";
      document.getElementById("change").innerHTML = "切换为铅笔";
      cuxi.innerHTML = `当前橡皮擦${ctx.lineWidth}`;
    }
  };
  document.getElementById("AllClean").onclick = function () {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  };
  document.getElementById("Pdel").onclick = function () {
    ctx.lineWidth--;
    cuxi.innerHTML = `当前铅笔${ctx.lineWidth}`;
  };
  document.getElementById("Padd").onclick = function () {
    ctx.lineWidth++;
    cuxi.innerHTML = `当前铅笔${ctx.lineWidth}`;
  };

  function dataURLtoFile(base64Str, fileName) {
    var arr = base64Str.split(","),
      mime = arr[0].match(/:(.*?);/)[1], //base64解析出来的图片类型
      bstr = atob(arr[1]), //对base64串进行操作，去掉url头，并转换为byte   atob为window内置方法
      len = bstr.length,
      ab = new ArrayBuffer(len), //将ASCII码小于0的转换为大于0
      u8arr = new Uint8Array(ab); //
    while (len--) {
      u8arr[len] = bstr.charCodeAt(len);
    }
    // 创建新的 File 对象实例[utf-8内容，文件名称或者路径，[可选参数，type：文件中的内容mime类型]]
    return new File([u8arr], fileName, {
      type: mime,
    });
  }
  let c = JSON.stringify({
    name: "111",
  });
  document.getElementById("upload").onclick = function () {
    // console.log(canvas.toDataURL().split(',')[1]);
    // url = './1678790435295.png'
    let formData = new FormData();
    var myfile = dataURLtoFile(canvas.toDataURL(), Date.now() + ".png");
    console.log(myfile);
    formData.append("file", myfile, "aaa.png");
    // console.log(formData.get('file'))
    // console.log(formData.get('file'))
    // document.getElementById('testimg').setAttribute('src',iurl)
    fetch("http://localhost:3000/upload/album", {
      method: "PUT",
      body: formData,
    })
      .then((res) => res.text())
      .then((res) => console.log(res));
  };
};
</script> -->
<style lang=""></style>
